package com.threeti.mecool.mobile.interfaces.assembler;

import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.project.Project;
import com.threeti.mecool.core.domain.model.project.ProjectStore;
import com.threeti.mecool.core.domain.model.sellinto.SellInto;
import com.threeti.mecool.core.infrastructure.persistence.SellIntoRepository;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.mobile.interfaces.dto.ProjectStoreWithSellIntoDto;
import com.threeti.mecool.mobile.interfaces.dto.ProjectWithStoresAndSellIntoDto;
import com.threeti.mecool.mobile.interfaces.dto.SellIntoDto;
import com.threeti.mecool.mobile.util.DozerMapperSingleton;
import org.dozer.Mapper;
import org.springframework.util.CollectionUtils;

import java.util.List;

public abstract class SellIntoAssembler {

    public static SellIntoDto toDto(SellInto srcDom) {
        Mapper transfer = DozerMapperSingleton.getInstance();
        SellIntoDto destDto = new SellIntoDto();
        transfer.map(srcDom, destDto);
        return destDto;
    }

    public static SellInto toDom(SellIntoDto srcDto) {
        Mapper transfer = DozerMapperSingleton.getInstance();
        SellInto destDom = new SellInto();
        transfer.map(srcDto, destDom);
        return destDom;
    }

    public static ProjectStoreWithSellIntoDto toDto(ProjectStore srcDom, SellIntoRepository sellIntoRepo) {
        Mapper transfer = DozerMapperSingleton.getInstance();
        ProjectStoreWithSellIntoDto destDto = new ProjectStoreWithSellIntoDto();
        transfer.map(srcDom, destDto);

        SellInto sellInto = sellIntoRepo.findByProjectStoreId(srcDom.getId());
        if (sellInto != null) {
            destDto.setSellInto(toDto(sellInto));
        } else {
            destDto.setSellInto(new SellIntoDto());//门店未卖进时,快速存储些模板空数据,以便维护
        }

        return destDto;
    }

    public static List<ProjectWithStoresAndSellIntoDto> toDtoList(List<Project> srcDoms, User user, ProjectService projService, SellIntoRepository sellIntoRepo) {
        List<ProjectWithStoresAndSellIntoDto> dtos = Lists.newArrayList();

        for (Project project : srcDoms) {
            if (project != null && project.getId() != null) {
                ProjectWithStoresAndSellIntoDto projectDto = ProjectAssembler.toDto1(project);

                List<ProjectStore> stores = projService.findStoresPreAssignedToUserWithinTheProject(user, project.getId());
                if (!CollectionUtils.isEmpty(stores)) {
                    for (ProjectStore projectStore : stores) {
                        projectDto.addProjectStoreDto(toDto(projectStore, sellIntoRepo));
                    }
                    dtos.add(projectDto);
                }
            }
        }
        return dtos;
    }
}
